import React, { useState } from 'react';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { Card, Input, Button, Spin, message } from 'antd';
import { useNavigate } from 'react-router-dom';
import "../static/css/Login.css";
import axios from 'axios';
import servicePath from "../config/apiUrl"

function Login() {
    const [userName, setUserName] = useState('');
    const [password, setPassword] = useState('');
    const [isLoading, setIsLoading] = useState('');
    const navigate = useNavigate();

    const checkLogin = () => {
        setIsLoading(true);

        if (!userName) {
            message.error('用户名不能为空');
            setTimeout(() => {
                setIsLoading(false);
            }, 500);
            return;
        } else if (!password) {
            message.error('密码不能为空');
            setTimeout(() => {
                setIsLoading(false);
            }, 500);
            return;
        }
        let data = {
            userName,
            password
        }
        axios({
            method: 'post',
            url: servicePath.checkLogin,
            data,
            withCredentials: true
        }).then(res => {
            const { code, msg, data } = res.data;
            if (code === 0) {
                message.success(msg);
                localStorage.setItem('openId', data.openId);
                navigate('/index?name=tom&age=20'); // 方式一
                // navigate("/index", { state: { name: 'tom', age: "20" }}); // 方式二 state 参数不显示url上面但是刷新会丢失数据
            } else {
                message.error("用户名密码错误");
                setTimeout(() => {
                    setIsLoading(false);
                }, 500);
            }
        });
    }

    return (
        <div className='login-div'>
            <Spin tip="Loading..." spinning={isLoading}>
                <Card title="红石榴21 Blog System" bordered={true} style={{ width: 400 }}>
                    <Input
                        id='userName'
                        size='large'
                        placeholder='Enter your userName'
                        prefix={<UserOutlined className="site-form-item-icon" />}
                        onChange={(e) => { setUserName(e.target.value) }}
                    />
                    <br /><br />
                    <Input
                        id='password'
                        type='password'
                        size='large'
                        placeholder='Enter your password'
                        prefix={<LockOutlined className="site-form-item-icon" />}
                        onChange={(e) => { setPassword(e.target.value) }}
                    />
                    <br /><br />
                    <Button type='primary' size='large' block onClick={checkLogin}> Login in </Button>
                </Card>
            </Spin>
        </div>
    )
}

export default Login;